package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.TestSoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.ReportType;
import com.tanhua.model.enums.SurveyType;
import com.tanhua.model.mongo.*;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class TestSoulService {

    private static String surveyName;   // 定义问卷类型

    @DubboReference
    private TestSoulApi testSoulApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    // 问卷列表
    public List<SurveyVo> testSoul() {
        // 调用api查询问卷信息
        List<Survey> list = testSoulApi.findSurvey();
        // 判断对象是否为空
        if (CollUtil.isEmpty(list)) {
            throw new BusinessException(ErrorResult.error());
        }
        // 定义返回集合
        List<SurveyVo> vos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            List<Questions> questionsList = testSoulApi.findQuestions(list.get(i).getSurveyId());

            List<QuestionsVo> questions = new ArrayList<>();
            // 创建QuestionsVo集合
            for (Questions question : questionsList) {
                // 根据问题id 查询选项集合
                List<Answer> answers = testSoulApi.findAnswer(question.getQuestionId());
                List<AnswerVo> answerVos = new ArrayList<>();
                for (Answer answer : answers) {
                    AnswerVo answerVo = AnswerVo.init(answer);
                    answerVos.add(answerVo);
                }
                QuestionsVo questionsVo = QuestionsVo.init(question, answerVos);
                questions.add(questionsVo);
            }
            // 创建SurveyVo对象
            SurveyVo vo = SurveyVo.init(list.get(i), questions);
            // 为结果加锁
            if (i > 0 && isExistType(UserHolder.getUserId(), i)) {
                vo.setIsLock(0);
            } else {
                vo.setIsLock(1);
            }
            if (i == 0) {
                vo.setIsLock(0);
            }
            vos.add(vo);
        }
        // 做题表查询做题记录
        for (int i = 0; i < vos.size() - 1; i++) {
            Work work = testSoulApi.findWork(UserHolder.getUserId(), i + 1);
            if(work != null){
                vos.get(i).setReportId(work.getReportId().toString());
            }
        }
        return vos;
    }

    public String testSbumit(List<HashMap> hashMaps) {
        // 定义分数
        Integer score = 0;
        // 遍历选项集
        for (HashMap map : hashMaps) {
            Long questionId = Long.valueOf(map.get("questionId").toString());
            Long optionId = Long.valueOf(map.get("optionId").toString());

            // 根据题类型获取灵魂类型
            Long surveyId = testSoulApi.findQuestion(questionId);
            Survey survey = testSoulApi.findSurvey(surveyId);
            surveyName = survey.getName();

            // 根据问题id和选项id查询选项详情
            Answer apiAnswer = testSoulApi.findAnswer(questionId, optionId);
            // 根据详情查询对应的分数
            Integer answerScore = apiAnswer.getScore();

            score += answerScore;
        }
        // 根据总分获取对应的判断类型
        Integer reportType = getScore(score);
        // 根据报告类型查询报告的详情
        Report apiByType = testSoulApi.findReport(reportType);

        // 将报告id返回
        return apiByType.getReportId().toString();
    }


    // 查看结果
    public ReportVo SeeReport(Long reportId) {

        // 根据报告id查询报告
        Report report = testSoulApi.findReport(reportId);
        // 获取默认维度
        List<DimensionsVo> dimensionsVoList = getDimensionsVoList();
        List<SimilarYouVo> similarYouVoList = new ArrayList<>();
        // 获取用户信息
        SimilarYouVo similarYouVo = new SimilarYouVo();
        // 设置用户id
        similarYouVo.setId(Integer.parseInt(UserHolder.getUserId().toString()));
        // 设置头像
        UserInfo userInfo = userInfoApi.findById(Long.valueOf(similarYouVo.getId()));
        similarYouVo.setAvatar(userInfo.getAvatar());
        // 根据id查询好友
        // similarYouVo.setAvatar(report.getCover());
        similarYouVoList.add(similarYouVo);

        if (!isExist(reportId, UserHolder.getUserId())) {
            // 保存做题记录
            Work userWork = new Work();
            BeanUtils.copyProperties(report, userWork);
            userWork.setUserId(UserHolder.getUserId());
            userWork.setSurveyType(getSurvey(surveyName));
            testSoulApi.saveWork(userWork);
        }

        // 构造返回结果
        ReportVo vo = ReportVo.init(report, dimensionsVoList, similarYouVoList);
        return vo;
    }

    // 根据问卷名称获取问卷类型
    public Integer getSurvey(String surveyNameme) {
        if ("初级灵魂题".equals(surveyNameme)) {
            return SurveyType.PRIMARY.getType();
        } else if ("中级灵魂题".equals(surveyNameme)) {
            return SurveyType.INTERMEDIATE.getType();
        } else {
            return SurveyType.SENIOR.getType();
        }
    }

    // 根据总得分判断类型
    private Integer getScore(Integer socer) {
        if (socer >= 20 && socer < 30) {
            return ReportType.OWL.getType();
        } else if (socer >= 30 && socer < 49) {
            return ReportType.RABBIT.getType();
        } else if (socer >= 50 && socer < 59) {
            return ReportType.FOX.getType();
        } else {
            return ReportType.LION.getType();
        }
    }

    // 创造返回维度条件
    private List<DimensionsVo> getDimensionsVoList() {

        List<DimensionsVo> dimensionsVoList = new ArrayList<>();

        DimensionsVo vo1 = new DimensionsVo();
        vo1.setKey("外向");
        vo1.setValue("80%");
        dimensionsVoList.add(vo1);

        DimensionsVo vo2 = new DimensionsVo();
        vo2.setKey("判断");
        vo2.setValue("70%");
        dimensionsVoList.add(vo2);

        DimensionsVo vo3 = new DimensionsVo();
        vo3.setKey("抽象");
        vo3.setValue("90%");
        dimensionsVoList.add(vo3);

        DimensionsVo vo4 = new DimensionsVo();
        vo4.setKey("理性");
        vo4.setValue("60%");
        dimensionsVoList.add(vo4);

        return dimensionsVoList;
    }


    // 查询做题报告是否生成
    public Boolean isExistType(Long userId, Integer surveyType) {
        return testSoulApi.findWorkById(userId, surveyType);
    }

    // 查询做题报告是否生成
    public Boolean isExist(Long reportId, Long userId) {
        return testSoulApi.findWorkById(reportId, userId);
    }

}
